package com.example.sharesinfo.fragment.trade;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.model.PositionModel;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class TradingPositionFragment extends BaseFragment {
    private TradingPositionFragment fa;
    private static final String LOGTAG = "TradingPositionFragment:";
    private static final int QUERYDATASUCCESS = 1001;
    private static final int QUERYDATAEMPTY = 1002;
    private RecyclerView mPositionView;
    private CommonAdapter<PositionModel> mPositionAdapter;
    private List<PositionModel> mList = new ArrayList<>();
    private View item_empty_view;
    //控件数据
    private TextView tv_own;
    private TextView tv_all;
    private TextView tv_useable;
    private TextView tv_today;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    JSONObject result = (JSONObject) msg.obj;
                    try {
                        JSONArray array = result.getJSONArray("data");
                        tv_own.setText(result.getString("SumMoney"));
                        tv_useable.setText(result.getString("ValidMoney"));
                        tv_all.setText(result.getString("SumStockValue"));
                        tv_today.setText(result.getString("Today_Profit_or_Loss"));
                        CommonUtils.setTextColor(tv_today,result.getString("Today_Profit_or_Loss"));
                        if (array.length() > 0) {
                            item_empty_view.setVisibility(View.GONE);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = (JSONObject) array.get(i);
                                PositionModel model = new PositionModel();
                                model.setId(object.getString("Id"));
                                model.setStockName(object.getString("StockName"));
                                model.setStockCode(object.getString("StockCode"));
                                model.setProfit_or_Loss_Value(object.getString("Profit_or_Loss_Value"));
                                model.setStockNumber(Integer.parseInt(object.getString("StockNumber")));
                                model.setNowPrice(Double.parseDouble(object.getString("NowPrice")));
                                mList.add(model);
                            }
                            mPositionAdapter.notifyDataSetChanged();
                        } else {
                            item_empty_view.setVisibility(View.VISIBLE);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case QUERYDATAEMPTY:
                    break;
            }
            return false;
        }
    });

    public TradingPositionFragment getFragment() {
        if (fa == null) {
            fa = new TradingPositionFragment();
        }
        return fa;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_trading_position, null);
        initView(view);
        queryData();
        return view;
    }


    private void initView(View view) {
        tv_own = view.findViewById(R.id.tv_own);
        tv_all = view.findViewById(R.id.tv_all);
        tv_useable = view.findViewById(R.id.tv_useable);
        tv_today = view.findViewById(R.id.tv_today);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mPositionView = view.findViewById(R.id.mPositionView);
        mPositionView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPositionView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mPositionAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<PositionModel>() {
            @Override
            public void onBindViewHolder(final PositionModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.stock_name, model.getStockName());
                viewHolder.setText(R.id.stock_earnings, model.getProfit_or_Loss_Value());
                viewHolder.setText(R.id.stock_code, model.getStockCode());
                viewHolder.setText(R.id.stock_position, String.valueOf(model.getStockNumber()));
                viewHolder.setText(R.id.stock_latest_price, String.valueOf(model.getNowPrice()));
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_earnings), model.getProfit_or_Loss_Value());
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_position), String.valueOf(model.getStockNumber()));
                CommonUtils.setTextColor((TextView) viewHolder.getView(R.id.stock_latest_price), String.valueOf(model.getNowPrice()));
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharesInfoActivity.startActivity(getContext(), model.getStockCode());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.trading_buy_sell_position_list_item;
            }
        });
        mPositionView.setAdapter(mPositionAdapter);
    }

    /**
     * 查询持仓的数据集
     */
    private void queryData() {
        String url = "http://119.23.221.142/api/account/GetPositionList?UserId=" +
                SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LOGTAG + s);
                JSONObject object = new JSONObject(s);
                message.what = QUERYDATASUCCESS;
                message.obj = object;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = QUERYDATAEMPTY;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }
}
